package cn.zyjblogs.sms.provider.baidu;

import cn.zyjblogs.sms.common.SmsRequest;
import cn.zyjblogs.sms.common.SmsResponse;
import cn.zyjblogs.sms.exception.SmsRuntimeException;
import cn.zyjblogs.sms.provider.AbstractSmsGranter;
import cn.zyjblogs.sms.provider.SmsGranter;
import cn.zyjblogs.sms.task.constant.ProviderType;
import cn.zyjblogs.sms.task.constant.SendStatus;
import cn.zyjblogs.sms.task.constant.TaskStatus;
import cn.zyjblogs.sms.task.dto.TaskResultDTO;
import cn.zyjblogs.starter.common.utils.collect.Lists;
import cn.zyjblogs.starter.common.utils.string.StringUtils;

import com.alibaba.fastjson2.JSON;
import com.baidubce.BceServiceException;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.sms.SmsClient;
import com.baidubce.services.sms.SmsClientConfiguration;
import com.baidubce.services.sms.model.SendMessageItem;
import com.baidubce.services.sms.model.SendMessageV3Request;
import com.baidubce.services.sms.model.SendMessageV3Response;
import java.util.Collections;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;


/**
 * @author zhuyijun
 */
public class BaiduBceSmsHandleGranter extends AbstractSmsGranter {
    private final Logger log = LoggerFactory.getLogger(BaiduBceSmsHandleGranter.class);
    private static final ProviderType PROVIDER_TYPE = ProviderType.BAIDU;
    public BaiduBceSmsHandleGranter() {
        super(PROVIDER_TYPE);
    }
    public BaiduBceSmsHandleGranter(ProviderType providerType) {
        super(providerType);
    }
    private static final String ENDPOINT = "http://smsv3.bj.baidubce.com";

    @Override
    public List<SmsResponse> sendSms(SmsRequest smsRequest) {
        return getSmsResponse(smsRequest);
    }


    private List<SmsResponse> getSmsResponse(SmsRequest smsRequest) {
        SmsClient client = createClient(smsRequest);
        SendMessageV3Request sendSmsRequest = new SendMessageV3Request();
        sendSmsRequest.setTemplate(smsRequest.getTemplateCode());
        sendSmsRequest.setContentVar(parseParam(smsRequest.getTemplateParams()));
        sendSmsRequest.setSignatureId(smsRequest.getSignName());
        sendSmsRequest.setCustom(smsRequest.getTaskId());
        try {
            sendSmsRequest.setMobile(String.join(",", smsRequest.getTelNums()));
            SendMessageV3Response sendMessageV3Response = client.sendMessage(sendSmsRequest);
            return assembleSendSmsResponse(sendMessageV3Response);
        } catch (Exception e) {
            log.error("发送短信失败 错误信息:{} ",e.getMessage());
            return Collections.emptyList();
        }
    }


    private List<SmsResponse> assembleSendSmsResponse(SendMessageV3Response sendMessageV3Response) {
        if (sendMessageV3Response == null || !sendMessageV3Response.isSuccess()) {
            return Collections.emptyList();
        }
        List<SmsResponse> responses = new LinkedList<>();
        List<SendMessageItem> data = sendMessageV3Response.getData();
        for (SendMessageItem sendStatus : data) {
            responses.add(SmsResponse.builder()
                    .code(sendStatus.getCode())
                    .phoneNumber(sendStatus.getMobile())
                    .bizId(sendStatus.getMessageId())
                    .sendStatus(ProviderType.BAIDU.getTaskStatus(sendStatus.getCode()))
                    .ext(sendMessageV3Response.getRequestId())
                    .message(sendStatus.getMessage())
                    .build());
        }
        return responses;
    }

    @SneakyThrows
    public static SmsClient createClient(SmsRequest smsRequest)  {
        SmsClientConfiguration config = new SmsClientConfiguration();
        config.setCredentials(new DefaultBceCredentials(smsRequest.getAccessKey(),smsRequest.getAccessSecret()));
        if (!StringUtils.isEmpty(smsRequest.getEndPoint())){
            config.setEndpoint(smsRequest.getEndPoint());
        } else {
            config.setEndpoint(ENDPOINT);
        }
        return new SmsClient(config);
    }


    @Override
    public SmsGranter getGranter(ProviderType providerType) {
        if (PROVIDER_TYPE.equals(providerType)) {
            return this;
        }
        return null;
    }
}
